package com.luoxiang.socialandroid.activity;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.ACCID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.adapter.RvgiftAdapter;
import com.luoxiang.socialandroid.base.BaseActivity;
import com.luoxiang.socialandroid.bean.BeforeCallBean;
import com.luoxiang.socialandroid.bean.GetMessageBean;
import com.luoxiang.socialandroid.bean.GetWhereBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.OurinfoBean;
import com.luoxiang.socialandroid.bean.RestCoinBean;
import com.luoxiang.socialandroid.common.bean.GiftBean;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.JZVideoPlayerStandardLoopVideo;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.lxj.xpopup.XPopup;
import com.netease.yunxin.kit.chatkit.ui.dialog.GiftDialog;
import com.netease.yunxin.kit.corekit.im.model.UserInfo;
import com.netease.yunxin.kit.corekit.im.utils.RouterConstant;
import com.netease.yunxin.kit.corekit.route.XKitRouter;
import com.netease.yunxin.nertc.ui.CallKitUI;
import com.netease.yunxin.nertc.ui.base.CallParam;

import org.salient.artplayer.MediaPlayerManager;
import org.salient.artplayer.VideoView;

import java.util.UUID;

import cn.jzvd.JzvdStd;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class VedioActivity extends BaseActivity {
    private JZVideoPlayerStandardLoopVideo vv;
    private ImageView im_shiping, icon_back;
    private Boolean isplay = false;
    private TextView tx_jinruzhuye;
    private int userid;
    private Button bt_sixin, bt_vedio_follow, bt_shipin;
    private int flag;
    private String token;
    private TextView tv_namevideo;
    private Button bt_liwu;
    private RecyclerView rv_gifts;
    private RvgiftAdapter adapter;
    private TextView now_coin;
    private Button btn_sendgift;
    private ImageView im_head_vedio;

    @Override
    protected void initListener() {
//        startviedio();
        todetails();
        tosixin(userid);
        icon_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        bt_vedio_follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (flag == 0) {
                    flag = 1;
                    getfocus(EXTRA, token, userid, 1);
                    isguanzhu();
                } else {
                    flag = 0;
                    getfocus(EXTRA, token, userid, 0);
                    isguanzhu();
                }
            }
        });
        bt_shipin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //点击视频
                //点击跳转视频通话
                getimPre(EXTRA, userid + "", token);
            }
        });
        bt_liwu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new XPopup.Builder(VedioActivity.this)
                        .moveUpToKeyboard(true)
                        .asCustom(new GiftDialog(VedioActivity.this, userid + "", 3, "0"))
                        .show();
            }
        });
        im_head_vedio.setOnClickListener(v -> {
            //点击头像跳转主页
            Intent intent = new Intent(VedioActivity.this, DetailsActivity.class);
            intent.putExtra("userid", userid);
            startActivity(intent);
        });
    }


    private void getimPre(String extra, String toUserId, String token) {
        NetUtils.getInstance().getApiService().getimPre(extra, toUserId, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        com.blankj.utilcode.util.LogUtils.i("decryptStr10", decryptStr);
                        Gson gson = new Gson();
                        OurinfoBean bean = gson.fromJson(decryptStr, OurinfoBean.class);
                        TestActivity.ourinfoBean = bean;
                        if (bean.getCode() == 0) {
                            //可以发起通话
                            int accId = com.luoxiang.lib_common.utils.MmkvUtil.INSTANCE.decodeInt(ACCID);
                            String id = UUID.randomUUID().toString().replace("-","");
                            CallParam param = CallParam.createSingleCallParam(2, accId + "", userid + "",null,null,id);
                            CallKitUI.startSingleCall(VedioActivity.this, param);
                        } else {
                            ToastUtils.showShort(bean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void tosixin(int userid) {
        bt_sixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (userid != -1) {
                    XKitRouter.withKey(RouterConstant.PATH_CHAT_P2P_PAGE).withParam(RouterConstant.CHAT_KRY, new UserInfo(userid + "", "aaa", "")).withContext(VedioActivity.this).navigate();
                }
            }
        });
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        setContentView(R.layout.activity_vedio);
        setStatusBarTranslucent();
    }

    @Override
    protected void initView() {
        im_head_vedio = findViewById(R.id.im_head_vedio);
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        Intent intent = getIntent();
        String urls = intent.getStringExtra("urls");
        userid = intent.getIntExtra("userid", 0);
        String username = intent.getStringExtra("username");
        String usericon = intent.getStringExtra("usericon");

        LogUtils.i("vediourul", urls);
        vv = findViewById(R.id.vv);
        icon_back = findViewById(R.id.icon_back);
        im_shiping = findViewById(R.id.im_shiping);
        tx_jinruzhuye = findViewById(R.id.tx_jinruzhuye);
        bt_sixin = findViewById(R.id.bt_sixin);
        bt_vedio_follow = findViewById(R.id.bt_vedio_follow);
        tv_namevideo = findViewById(R.id.tv_namevideo);
        bt_shipin = findViewById(R.id.bt_shipin);
        bt_liwu = findViewById(R.id.bt_liwu);
        vv.setUp(urls, "");
        vv.startVideo();
        MediaPlayerManager.instance().setLooping(true); //循环
        vv.setVideoImageDisplayType(vv.VIDEO_IMAGE_DISPLAY_TYPE_FILL_SCROP);

        //调用是否关注
        getwhetherFocus(EXTRA, userid, token);
        tv_namevideo.setText(username);
        if (usericon != null) {
            Glide.with(VedioActivity.this)
                    .load("https://dahuixiong.oss-cn-shenzhen.aliyuncs.com/" + usericon)
                    .circleCrop()
                    .into(im_head_vedio);
        }


    }

    private void isguanzhu() {
        //是否关注
        if (flag == 0) {
            //未关注
            bt_vedio_follow.setBackgroundResource(R.drawable.shepe_btnguanzhu);
            bt_vedio_follow.setText(R.string.mi_guanzhu);
            bt_vedio_follow.setTextColor(Color.parseColor("#FFFFFF"));
        } else {
            //已关注
            bt_vedio_follow.setBackgroundResource(R.drawable.shape_noguanzhu);
            bt_vedio_follow.setText(R.string.mi_yiguanzhu);
            bt_vedio_follow.setTextColor(Color.parseColor("#999999"));

        }
    }

    //关注的方法
    private void getfocus(String extra, String token, int toUserId, int type) {
        NetUtils.getInstance().getApiService().getfocus(extra, token, toUserId, type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        com.blankj.utilcode.util.LogUtils.i("decryptStr10", decryptStr);
                        Gson gson = new Gson();
                        GetMessageBean getWhereBean = gson.fromJson(decryptStr, GetMessageBean.class);
                        if (getWhereBean.getCode() != 0) {
                            ToastUtils.showShort(getWhereBean.getMsg());
                            getwhetherFocus(EXTRA, userid, token);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getwhetherFocus(String extra, int userId, String token) {
        getRequest();
        NetUtils.getInstance().getApiService().getwhetherFocus(extra, userId, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        clearLoading();
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        com.blankj.utilcode.util.LogUtils.i("decryptStr9", decryptStr);
                        Gson gson = new Gson();
                        GetWhereBean getWhereBean = gson.fromJson(decryptStr, GetWhereBean.class);
                        if (getWhereBean != null) {
                            if (getWhereBean.getData() != null) {
                                flag = getWhereBean.getData().getFlag();
                                int show = getWhereBean.getData().isShow();
                                if (show!=1){
                                    //隐藏控件
                                    bt_vedio_follow.setVisibility(View.GONE);
                                    bt_sixin.setVisibility(View.GONE);
                                    bt_liwu.setVisibility(View.GONE);
                                    bt_shipin.setVisibility(View.GONE);
                                }else {
                                    //展示控件
                                    bt_vedio_follow.setVisibility(View.VISIBLE);
                                    bt_sixin.setVisibility(View.VISIBLE);
                                    bt_liwu.setVisibility(View.VISIBLE);
                                    bt_shipin.setVisibility(View.VISIBLE);
                                }
                            }
                        }
                        isguanzhu();
                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //视频播放
    private void startviedio() {
        vv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isplay) {
                    isplay = false;
                    im_shiping.setVisibility(View.GONE);
                    MediaPlayerManager.instance().start();//开始
                } else {
                    isplay = true;
                    im_shiping.setVisibility(View.VISIBLE);
                    MediaPlayerManager.instance().pause();//暂停
                }
            }
        });
    }

    private void todetails() {
        tx_jinruzhuye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(VedioActivity.this, DetailsActivity.class);
                intent.putExtra("userid", userid);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        vv.reset();
    }

    @Override
    protected void onPause() {
        super.onPause();
        vv.reset();
    }
}
